import bus from '@/lib/bus'

String.prototype.toRgbFormat = function () {
    var sColor = this.toLowerCase();
    //十六进制颜色值的正则表达式
    var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
    // 如果是16进制颜色
    if (sColor && reg.test(sColor)) {
        if (sColor.length === 4) {
            var sColorNew = "#";
            for (var i = 1; i < 4; i += 1) {
                sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
            }
            sColor = sColorNew;
        }
        //处理六位的颜色值
        var sColorChange = [];
        for (var i = 1; i < 7; i += 2) {
            sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
        }
        return {
            red: sColorChange[0],
            green: sColorChange[1],
            blue: sColorChange[2]
        };
    }
    return {
        red: sColorChange[0],
        green: sColorChange[1],
        blue: sColorChange[2]
    };
};

Array.prototype.tail = function () {
    return this[this.length - 1];
}

const directiveHash = {
    remove: {
        'poi': 'RemovePOI',
        'path': 'RemovePath',
        'range': 'RemoveRange',
        'heatmap': 'RemoveHeatMap',
        'roadheatmap': 'RoadHeatMap',
        'migrationmap': 'MigrationMap'
    }
}
export const clearAllElement = (callback) => {
    window.cloudRender.SuperAPI('RemoveAllPOI');
    window.cloudRender.SuperAPI('RemoveAllPath');
    window.cloudRender.SuperAPI('RemoveAllRange');
    window.cloudRender.SuperAPI('RemoveAllHeatMap');
    window.cloudRender.SuperAPI("RemoveAllColumnHeatMap");
    window.cloudRender.SuperAPI("RemoveAllSpaceHeatMap")
    window.cloudRender.SuperAPI("RemoveAllRoadHeatMap")
    window.cloudRender.SuperAPI("RemoveAllMigrationMap")
    window.cloudRender.SuperAPI("RemoveAllStrategyMap")
    window.cloudRender.SuperAPI('RemoveAllEffect');
    if (callback) {
        callback();
    }
}

export const clearElement = (type, idList, callback) => {
    idList.forEach(item => {
        window.cloudRender.SuperAPI(directiveHash.remove[type], {
            id: item
        });
    });
    if (callback) {
        callback();
    }
}
export const doPOIMove = (poi, path) => {
    const scriptList = path.map(o => o.coord);
    let pathList = [];
    let headNode = null;
    headNode = scriptList.shift();
    window.cloudRender.SuperAPI('RemovePOI', {
        id: poi.id
    });
    window.cloudRender.SuperAPI('AddCustomPOI', poi);
    // updateCustomPOICoord容易导致poi创建重复，目前原因未知，因此先采用在POI迁徙的第一步，采用删除、再添加的方式，先做初始化。
    pathList.push(headNode);
    const autoTickFunction = () => {
        headNode = scriptList.shift();
        window.cloudRender.SuperAPI('UpdateCustomPOICoord', {
            id: poi.id,
            coord_type: 0,
            cad_mapkey: '',
            coord: headNode,
            coord_z: 0
        });
        pathList.push(headNode);
    }

    const autoTick = setInterval(() => {
        if (scriptList.length === 0) {
            clearInterval(autoTick);
        } else {
            autoTickFunction();
        }
    }, 2000);
}

export const doPOIMigration = (poiStart, poiEnd, path) => {
    const scriptList = path.map(o => o.coord);
    const pathList = [];
    let headNode = null;
    window.cloudRender.SuperAPI('AddMigrationMap', {
        "id": poiStart.id + '_' + poiEnd.id,
        "coord_type": 0, //坐标类型(0:经纬度坐标, 1:cad坐标)
        "cad_mapkey": "", //CAD基准点Key值, 项目中约定
        "type": 2, //样式类型(1:波浪线型, 2:箭头型, 3:射线)
        "start_coord": poiStart.coord, //起点坐标 lng,lat
        "start_coord_z": 1, //起点高度(米)
        "targetdata": [{
            "target_coord": poiEnd.coord, //目标点坐标 lng,lat
            "target_coord_z": 1, //目标点高度(米)
            "mark_size": 30, //目标点标志直径(米)
            "mark_color": "ff0000", //目标点颜色(HEX颜色值)
            "line_width": 30, //连线宽度(米)(注:样式类型 type:3时, line_width参数为连线数量, 范围 5 ~ 100)
            "line_color": "ff0000", //连线颜色(HEX颜色值)
            "curvature": 0.6 //连线曲度调节(取值范围 -1 ~ 1, 0为默认曲度, 此值越小曲线越平, 反之曲线越陡峭)
        }]
    }, e => {
        headNode = scriptList.shift();
        window.cloudRender.SuperAPI('RemovePOI', {
            id: poiStart.id
        });
        window.cloudRender.SuperAPI('AddCustomPOI', poiStart);
        // updateCustomPOICoord容易导致poi创建重复，目前原因未知，因此先采用在POI迁徙的第一步，采用删除、再添加的方式，先做初始化。
        pathList.push(headNode);
    });
    window.cloudRender.SuperAPI('FocusMigrationMap', {
        id: poiStart.id + '_' + poiEnd.id,
        distance: 200
    });
    let autoTickFunction = () => {
        headNode = scriptList.shift();
        window.cloudRender.SuperAPI('UpdateCustomPOICoord', {
            id: poiStart.id,
            coord_type: 0,
            cad_mapkey: '',
            coord: headNode,
            coord_z: poiStart.coord_z
        });
        window.cloudRender.SuperAPI('UpdateMigrationMapCoord', {
            "id": poiStart.id + '_' + poiEnd.id,
            "coord_type": 0, //坐标类型(0:经纬度坐标, 1:cad坐标)
            "cad_mapkey": "", //CAD基准点Key值, 项目中约定
            "start_coord": headNode, //起点坐标 lng,lat
            "start_coord_z": 1, //起点高度(米)
            "targetdata": [{
                "target_coord": poiEnd.coord, //目标点坐标
                "target_coord_z": 1 //目标点高度(米)
            }]
        })
        pathList.push(headNode);
        if (pathList.length === 2) {
            window.cloudRender.SuperAPI('AddPath', {
                "id": poiStart.id + '_' + poiEnd.id + '_path',
                "coord_type": 0, //坐标类型(0:经纬度坐标, 1:cad坐标)
                "cad_mapkey": "", //CAD基准点Key值, 项目中约定
                "type": "arrow", //样式类型; 注①
                "color": "ff0000", //颜色(HEX颜色值)
                "width": 20, //宽度(米)
                "points": pathList.map(o => {
                    return {
                        coord: o,
                        coord_z: 10
                    }
                })
            });
        } else if (pathList.length > 2) {
            window.cloudRender.SuperAPI('UpdatePathCoord', {
                "id": poiStart.id + '_' + poiEnd.id + '_path',
                "coord_type": 0, //坐标类型(0:经纬度坐标, 1:cad坐标)
                "cad_mapkey": "", //CAD基准点Key值, 项目中约定
                "points": pathList.map(o => {
                    return {
                        coord: o,
                        coord_z: 10
                    }
                })
            })
        }
    };
    let autoTick = setInterval(() => {
        if (scriptList.length === 0) {
            clearInterval(autoTick);
            window.cloudRender.SuperAPI('RemoveMigrationMap', {
                id: poiStart.id + '_' + poiEnd.id
            });
            window.cloudRender.SuperAPI('RemovePath', {
                id: poiStart.id + '_' + poiEnd.id + '_path'
            })
        } else {
            autoTickFunction();
        }
    }, 1000);
}

export const busEventHandle = (eventName, callback) => {
    bus.$off(eventName);
    if (callback) {
        bus.$on(eventName, callback);
    }
}

export const busEventDispatch = (eventName) => {
    bus.$off(eventName)
}

export const busEventEmit = (eventName, data) => {
    bus.$emit(eventName, data);
}

export const windowEventHandle = (posterOrigin, callback) => {
    let fn = (msg) => {
        if (msg.origin === posterOrigin) {
            callback(msg);
        }
    }
    window.removeEventListener('message', fn);
    window.addEventListener('message', fn);
}

export const getDistance = (lat1, lng1, lat2, lng2) => {
    let radLat1 = toRadians(lat1);
    let radLat2 = toRadians(lat2);
    let deltaLat = radLat1 - radLat2;
    let deltaLng = toRadians(lng1) - toRadians(lng2);
    let dis = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(deltaLat / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(deltaLng / 2), 2)));
    return dis * 6378.137 * 1000;

    function toRadians(d) {
        return d * Math.PI / 180;
    }
}

export const RGB2HSL = (r, g, b) => {
    r /= 255, g /= 255, b /= 255;
    var max = Math.max(r, g, b),
        min = Math.min(r, g, b);
    var h, s, l = (max + min) / 2;

    if (max == min) {
        h = s = 0; // achromatic
    } else {
        var d = max - min;
        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
        switch (max) {
            case r:
                h = (g - b) / d + (g < b ? 6 : 0);
                break;
            case g:
                h = (b - r) / d + 2;
                break;
            case b:
                h = (r - g) / d + 4;
                break;
        }
        h /= 6;
    }

    return {
        h,
        s,
        l
    };
}

export const HEX2HSL = (hexString) => {
    let rgbColor = hexString.toRgbFormat();
    let result = RGB2HSL(rgbColor.red, rgbColor.green, rgbColor.blue);
    return result;
}

export const HSL2HEX = (h, s, l) => {
    var r, g, b;
    if (s == 0) {
        r = g = b = l; // achromatic
    } else {
        var hue2rgb = function hue2rgb(p, q, t) {
            if (t < 0) t += 1;
            if (t > 1) t -= 1;
            if (t < 1 / 6) return p + (q - p) * 6 * t;
            if (t < 1 / 2) return q;
            if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
            return p;
        };

        var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        var p = 2 * l - q;
        r = hue2rgb(p, q, h + 1 / 3);
        g = hue2rgb(p, q, h);
        b = hue2rgb(p, q, h - 1 / 3);
    }
    let rgbValue = [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
    return "#" + ((1 << 24) + (rgbValue[0] << 16) + (rgbValue[1] << 8) + rgbValue[2]).toString(16).slice(1);
}

export const calculateColorBrightness = (color, brightnessOffset) => {
    let hslObject = HEX2HSL(color);
    let hexString = HSL2HEX(hslObject.h, hslObject.s, hslObject.l + (brightnessOffset / 100));
    return hexString;
}


export const timeShift = (offset, mode) => {
    //单位为分钟
    let now = new Date()
    let newTime = new Date(now.getTime() + (offset * 60 * 1000))
    let obj = {
        year: newTime.getFullYear(),
        month: (newTime.getMonth() + 1 < 10) ? '0' + (newTime.getMonth() + 1) : newTime.getMonth() + 1,
        day: newTime.getDate() < 10 ? '0' + newTime.getDate() : newTime.getDate(),
        hour: newTime.getHours() < 10 ? '0' + newTime.getHours() : newTime.getHours(),
        minute: newTime.getMinutes() < 10 ? '0' + newTime.getMinutes() : newTime.getMinutes(),
        seconds: newTime.getSeconds() < 10 ? '0' + newTime.getSeconds() : newTime.getSeconds()
    }
    let resultString = null;
    if (mode === 'simple') {
        resultString = `${obj.hour}:${obj.minute}:${obj.seconds}`;
    } else {
        resultString = `${obj.year}/${obj.month}/${obj.day} ${obj.hour}:${obj.minute}:${obj.seconds}`;
    }
    return resultString;
}

export const clone = (data) => {
    return JSON.parse(JSON.stringify(data));
}